package com.bilin.coin.activity;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.utils.TextUtils;
import com.bilin.coin.network.RetrofitConfig;
import com.bilin.coin.utils.DeviceIdUtil;
import com.bilin.coin.utils.MobilePhoneDeviceInfo;
import com.bilin.coin.utils.StatusBarUtil;
import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.bilin.coin.ApiConstant;
import com.bilin.coin.BuildConfig;
import com.bilin.coin.MainActivity;
import com.bilin.coin.R;
import com.bilin.coin.bean.CommonSuccessEvent;
import com.bilin.coin.bean.LoginBean;
import com.bilin.coin.common.base.BaseAppCompatActivity;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.callback.CommonCallBack;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.GsonUtil;
import com.bilin.coin.utils.SharedPreferencesUtils;
import com.bilin.coin.utils.TimerUtils;
import com.umeng.commonsdk.utils.UMUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import kt.com.bilin.coin.common.UserDataCache;
import kt.com.bilin.coin.helper.mohsi.MoshiUtils;
import kt.com.bilin.coin.utils.Logger;

@Route(path = "/auction/LoginActivity")
public class LoginActivity extends BaseAppCompatActivity {

    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_pass)
    EditText et_pass;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.rl_send)
    RelativeLayout rl_send;
    @BindView(R.id.v_send)
    View v_send;
    @BindView(R.id.bt_send)
    TextView bt_send;


    @Override
    protected void initView() {

        setTitle(getResources().getString(R.string.login));
        rl_send.setVisibility(View.GONE);
        v_send.setVisibility(View.GONE);
        if (BuildConfig.DEBUG) {
            //et_phone.setText("13112362573");//18202729071
            et_phone.setText("17620410531");//18202729071
            et_pass.setText("123456");//123123
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public boolean isShowToolBar() {
        return true;
    }


    @OnClick({R.id.tv_forget_pass, R.id.bt_send, R.id.bt_confirm,
            R.id.tv_create, R.id.tv_protocol_user,
            R.id.tv_protocol_private, R.id.tv_unbind})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_unbind:
                baseStartActivity("/auction/UnbindActivity");
                break;
            //找回密码
            case R.id.tv_forget_pass:
                baseStartActivity("/confirm/confirm/FindBackActivity");
                break;
            //登录
            case R.id.bt_confirm:
                if (rl_send.getVisibility() == View.GONE) {
                    login();
                } else {
                    loginWithCode();
                }
                break;
            case R.id.tv_create:
                baseStartActivity("/auction/RegisterActivity");
                break;
            case R.id.bt_send:
                sendRegCode();
                break;
            case R.id.tv_protocol_user:
                jumpProtocol(RetrofitConfig.newsUrl + "0", "用户协议");
                break;
            case R.id.tv_protocol_private:
                jumpProtocol(ApiConstant.PRIVACY_PROTOCOL, "隐私协议");
                break;
        }
    }

    private void loginWithCode() {
        String code = et_code.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            showToast(getResources().getString(R.string.sms_code_empty));
            return;
        }
        DialogUtils.showDialogLoading(this);
        RequestUtils
                .post()
                .url(ApiConstant.LOGIN2)
                .addParams("code", code)
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {

                    @Override
                    protected void onError(String errorMsg) {
                        DialogUtils.dismissDialogLoading();
                        showToast(errorMsg);
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        LoginBean loginBean = RequestUtils.getGson().fromJson(dataJson, LoginBean.class);
                        showToast(getResources().getString(R.string.login_success));
                        //记录登录信息
                        saveUserInfo(loginBean);
                        dataJson = dataJson == null || "".equals(dataJson) ? "{}" : dataJson;
                        UserDataCache.INSTANCE.setLoginInfo(MoshiUtils.parseObject(dataJson, kt.com.bilin.coin.bean.LoginBean.class));
                        DialogUtils.dismissDialogLoading();
                        EventBus.getDefault().post(new CommonSuccessEvent(CommonSuccessEvent.LoginSuccess));
                        finish();
                    }

                    @Override
                    protected void onCallBackError(Throwable e) {
                        showMsg(e);
                        DialogUtils.dismissDialogLoading();
                    }
                });

    }

    private void saveUserInfo(LoginBean loginBean) {
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.CSRF_TOKEN, loginBean.getCsrfToken());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.LoginSmsToken, loginBean.getLoginSmsToken());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.Mobile, loginBean.getUserInfo().getMobile());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsHasSafeWord, loginBean.getUserInfo().isHasSafeWord());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsLogin, loginBean.getUserInfo().isLogin());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USER_ID, loginBean.getUserInfo().getId());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USERINFO_JSON, GsonUtil.GsonString(loginBean.getUserInfo()));
    }


    /**
     * 发送短信验证码
     */
    public void sendRegCode() {
        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showToast(getResources().getString(R.string.phone_empty));
            return;
        }
        DialogUtils.showDialogLoading(this);
        RequestUtils
                .post()
                .url(ApiConstant.LOGIN_SMS)
                .addParams("mobile", phone)
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {


                    @Override
                    protected void onError(String errorMsg) {
                        showToast(errorMsg);
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        TimerUtils.getInitialise().startTimer(bt_send, 120, getString(R.string.login_resend_code));
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    public void onCallBackError(Throwable e) {
                        DialogUtils.dismissDialogLoading();
                        showMsg(e);

                    }
                });
    }

    public void login() {
        String pass = et_pass.getText().toString().trim();
        String phone = et_phone.getText().toString().trim();

        if (TextUtils.isEmpty(phone)) {
            showToast(getResources().getString(R.string.phone_empty));
            return;
        }
        if (TextUtils.isEmpty(pass)) {
            showToast(getResources().getString(R.string.pass_empty));
            return;
        }
        DialogUtils.showDialogLoading(this);
        RequestUtils
                .post()
                .url("/api/user/v2/login")
                .addParams("mobile", phone)
                .addParams("pwd", pass)
                .addParams("deviceCode", DeviceIdUtil.getDeviceId(this))
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {

                    @Override
                    protected void onError(String errorMsg) {
                        showToast(errorMsg);
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        LoginBean loginBean = RequestUtils.getGson().fromJson(dataJson, LoginBean.class);
                        if (loginBean.isIsNeedSecValid()) {
                            rl_send.setVisibility(View.VISIBLE);
                            v_send.setVisibility(View.VISIBLE);
                        } else {
                            showToast(getResources().getString(R.string.login_success));
                            saveUserInfo(loginBean);
                            dataJson = dataJson == null || "".equals(dataJson) ? "{}" : dataJson;
                            Logger.e("dataJson===>"+dataJson);
                            UserDataCache.INSTANCE.setLoginInfo(MoshiUtils.parseObject(dataJson, kt.com.bilin.coin.bean.LoginBean.class));
                            EventBus.getDefault().post(new CommonSuccessEvent(CommonSuccessEvent.LoginSuccess));
                            finish();
                        }
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onCallBackError(Throwable e) {
                        showMsg(e);
                        DialogUtils.dismissDialogLoading();
                    }
                });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((boolean) SharedPreferencesUtils.getInstance().getData("language_state", false)) {
                SharedPreferencesUtils.getInstance().saveData("language_state", false);
                Intent itMain = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(itMain);
                finish();
                overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
            } else {
                finish();
            }
        }
        return true;
    }

    private void jumpProtocol(String url, String title) {
        baseStartActivityWith("/common/WebPageLoading")
                .withString("url", url)
                .withString("title", title).navigation();
    }
}
